import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:markdown/markdown.dart' as md;

/// 括号分数的Markdown构建器，用于渲染括号中的分数
class BracketFractionBuilder extends MarkdownElementBuilder {
  final TextStyle? style;
  final double textScaleFactor;

  BracketFractionBuilder({
    this.style,
    this.textScaleFactor = 1.0,
  });

  @override
  Widget? visitElementAfter(md.Element element, TextStyle? preferredStyle) {
    if (element.tag != 'bracket_fraction') return null;

    final fractionText = element.textContent;
    return _buildFractionWidget(fractionText, preferredStyle);
  }

  /// 构建分数小部件
  Widget _buildFractionWidget(String fractionText, TextStyle? preferredStyle) {
    final TextStyle safeStyle = preferredStyle ?? style ?? const TextStyle(fontSize: 16.0);
    
    // 解析分数
    final fractionData = _parseFraction(fractionText);
    if (fractionData == null) {
      // 如果解析失败，返回原始文本
      return Text(fractionText, style: safeStyle);
    }

    return IntrinsicWidth(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 分子
          Container(
            alignment: Alignment.center,
            child: Text(
              fractionData['numerator']!,
              style: safeStyle,
              textAlign: TextAlign.center,
            ),
          ),
          // 分数线
          Container(
            height: 1.0,
            color: safeStyle.color ?? Colors.black,
            margin: const EdgeInsets.symmetric(vertical: 2.0),
          ),
          // 分母
          Container(
            alignment: Alignment.center,
            child: Text(
              fractionData['denominator']!,
              style: safeStyle,
              textAlign: TextAlign.center,
            ),
          ),
        ],
      ),
    );
  }

  /// 解析分数文本，提取分子和分母
  Map<String, String>? _parseFraction(String fractionText) {
    // 移除外层括号
    String content = fractionText;
    if (content.startsWith('(') || content.startsWith('（')) {
      content = content.substring(1);
    }
    if (content.endsWith(')') || content.endsWith('）')) {
      content = content.substring(0, content.length - 1);
    }
    
    // 查找分数线位置
    final slashIndex = content.indexOf('/');
    if (slashIndex == -1) return null;
    
    String numerator = content.substring(0, slashIndex).trim();
    String denominator = content.substring(slashIndex + 1).trim();
    
    // 处理分子中的括号
    if (numerator.startsWith('(') && numerator.endsWith(')')) {
      numerator = numerator.substring(1, numerator.length - 1).trim();
    }
    
    // 处理分母中的括号
    if (denominator.startsWith('(') && denominator.endsWith(')')) {
      denominator = denominator.substring(1, denominator.length - 1).trim();
    }
    
    return {
      'numerator': numerator,
      'denominator': denominator,
    };
  }
}